package com.example.weatherapp;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.weatherapp.adapter.DailyAdapter;
import com.example.weatherapp.adapter.HourlyAdapter;
import com.example.weatherapp.beans.DailyItemBean;
import com.example.weatherapp.beans.HourlyItemBean;
import com.example.weatherapp.beans.PlaceBean;
import com.example.weatherapp.beans.WeatherDaily;
import com.example.weatherapp.beans.WeatherHourly;
import com.example.weatherapp.beans.WeatherRealtime;
import com.example.weatherapp.utils.WeatherUtil;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WeatherResultActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private CollapsingToolbarLayout collapsingToolbar;
    // 默认城市及经纬度
    private String city = "天津市";
    private double lat = 39.085318;
    private double lng = 117.201509;

    private TextView tvTempRealtime, tvTempMaxMin, tvDescription ,tvPlace, tvWeather;
    private RecyclerView rvHourly, rvDaily;
    private ImageView ivBackground;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ivBackground = findViewById(R.id.ivBackground);
        SharedPreferences preferences = getSharedPreferences("cities", MODE_PRIVATE);
        Integer theme = preferences.getInt("theme", R.mipmap.bg_main_theme1);
        ivBackground.setImageResource(theme);
        city = (String) getIntent().getExtras().get("city");
        lng = (double) getIntent().getExtras().get("lng");
        lat = (double) getIntent().getExtras().get("lat");
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//        collapsingToolbar = findViewById(R.id.collapsingToolbar);
//        collapsingToolbar.setTitle(city);
//        collapsingToolbar.setExpandedTitleColor(Color.WHITE);
//        collapsingToolbar.setCollapsedTitleTextColor(Color.WHITE);
        tvTempRealtime = findViewById(R.id.tvTempRealtime);
        tvTempMaxMin = findViewById(R.id.tvTempMaxMin);
        tvPlace = findViewById(R.id.tvPlace);
        tvPlace.setText(city);
        tvWeather = findViewById(R.id.tvWeather);
        tvDescription = findViewById(R.id.tvDescription);
        rvHourly = findViewById(R.id.rvHourly);
        rvDaily = findViewById(R.id.rvDaily);
        fetchWeatherData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu_result, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            case R.id.add_city:
                addCity();
                return true;
            case R.id.default_city:
                addCity();
                setDefault();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * 设置默认城市
     */
    private void setDefault() {
        SharedPreferences preferences = getSharedPreferences("cities", MODE_PRIVATE);
        preferences.edit().putString("city", city).putFloat("lat", (float) lat).putFloat("lng", (float) lng).commit();
    }

    /**
     * 添加城市
     */
    private void addCity() {
        SharedPreferences preferences = getSharedPreferences("cities", MODE_PRIVATE);
        String cityList = preferences.getString("cityList", "[]");
        Gson gson = new Gson();
        Type listType = new TypeToken<List<PlaceBean>>() {
        }.getType();
        List<PlaceBean> placeBeans = gson.fromJson(cityList, listType);
        for (PlaceBean placeBean : placeBeans) {
            if (placeBean.getName().equals(city)) {
                return;
            }
        }
        placeBeans.add(new PlaceBean(city, lat, lng));
        preferences.edit().putString("cityList", gson.toJson(placeBeans)).commit();
    }

    /**
     * 获取天气数据
     */
    private void fetchWeatherData() {
        // 获取默认城市实时天气数据
        getWeatherRealtime();
        // 获取默认城市天级别天气数据
        getWeatherDaily();
        // 获取默认城市小时级别天气数据
        getWeatherHourly();
    }

    /**
     * 获取实时天气数据
     */
    private void getWeatherRealtime() {
        try {
            OkHttpClient client = new OkHttpClient();
            String url = "https://api.caiyunapp.com/v2.5/VCdxijtyAdrjqrCd/" + lng + "," + lat + "/realtime.json";
            Request request = new Request.Builder().url(url).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String repContent = response.body().string();
                        Gson gson = new Gson();
                        WeatherRealtime weatherRealtime = gson.fromJson(repContent, WeatherRealtime.class);
                        runOnUiThread(() -> {
                            tvTempRealtime.setText((int) weatherRealtime.getResult().getRealtime().getTemperature() + "");
                            tvDescription.setText(WeatherUtil.genDescriptionBySkycon(weatherRealtime.getResult().getRealtime().getSkycon()) + "  空气" + weatherRealtime.getResult().getRealtime().getAir_quality().getDescription().getChn());
                            tvWeather.setText(WeatherUtil.genDescriptionBySkycon(weatherRealtime.getResult().getRealtime().getSkycon()));
                        });
                    } else {
                        Log.e(WeatherResultActivity.this.getLocalClassName(), "获取实时天气数据失败");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取天级别天气数据
     */
    private void getWeatherDaily() {
        try {
            OkHttpClient client = new OkHttpClient();
            String url = "https://api.caiyunapp.com/v2.6/GUyNFJ2UiAXvBqAo/" + lng + "," + lat + "/daily?dailysteps=3";
            Request request = new Request.Builder().url(url).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String repContent = response.body().string();
                        Gson gson = new Gson();
                        WeatherDaily weatherDaily = gson.fromJson(repContent, WeatherDaily.class);
                        runOnUiThread(() -> {
                            int max = (int) weatherDaily.getResult().getDaily().getTemperature().get(0).getMax();
                            int min = (int) weatherDaily.getResult().getDaily().getTemperature().get(0).getMin();
                            tvTempMaxMin.setText(max + " / " + min + "\u00AD°C");
                            // 多日预报
                            List<DailyItemBean> list = DailyItemBean.getList(weatherDaily);
                            LinearLayoutManager layoutManager = new LinearLayoutManager(WeatherResultActivity.this);
                            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                            rvDaily.setLayoutManager(layoutManager);
                            rvDaily.setAdapter(new DailyAdapter(list));

                        });
                    } else {
                        Log.e(WeatherResultActivity.this.getLocalClassName(), "获取天级别天气数据失败");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取小时级别天气数据
     */
    private void getWeatherHourly() {
        try {
            OkHttpClient client = new OkHttpClient();
            String url = "https://api.caiyunapp.com/v2.6/GUyNFJ2UiAXvBqAo/" + lng + "," + lat + "/hourly?hourlysteps=24";
            Request request = new Request.Builder().url(url).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String repContent = response.body().string();
                        Gson gson = new Gson();
                        WeatherHourly weatherHourly = gson.fromJson(repContent, WeatherHourly.class);
                        runOnUiThread(() -> {
                            List<HourlyItemBean> list = HourlyItemBean.getList(weatherHourly);
                            LinearLayoutManager layoutManager = new LinearLayoutManager(WeatherResultActivity.this);
                            layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                            rvHourly.setLayoutManager(layoutManager);
                            rvHourly.setAdapter(new HourlyAdapter(list));
                        });
                    } else {
                        Log.e(WeatherResultActivity.this.getLocalClassName(), "获取小时级别天气数据失败");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}